#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStandardItemModel>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    model = new QStandardItemModel(ui->treeView);
    ui->treeView->setModel(this->model);
    ui->treeView->setSelectionMode(QTreeView::SingleSelection);
    ui->treeView->setHeaderHidden(true);

//    QStandardItem *item = new QStandardItem("你好");
//    QStandardItem *item1 = new QStandardItem("世界");
//    QStandardItem *item2 = new QStandardItem("hi");
//    QStandardItem *item3 = new QStandardItem("good");
//    QStandardItem *item4 = new QStandardItem("idea");
//    model->appendRow(item);
//    item->appendRow(item1);
//    item1->appendRow(item2);
//    model->appendRow(item3);
//    item3->appendRow(item4);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    if(ui->lineEdit->text().length() == 0)
    {
        QMessageBox::information(this,QString("提示"),QString("必须输入内容"),QMessageBox::Yes);
        return;
    }
    QString itemtext = ui->lineEdit->text();
    ui->lineEdit->clear();
    // 如果列表元素为空则直接添加
    if(model->rowCount()==0){
        QStandardItem *item = new QStandardItem(itemtext);
        model->setItem(0,0,item);
    }
    // 列表不为空了添加
    else if(ui->treeView->currentIndex().isValid())
    {
        ui->treeView->currentIndex();
        model->itemFromIndex(ui->treeView->currentIndex())->appendRow(new QStandardItem(itemtext));
    }
    else
    {
        QMessageBox::information(this,QString("提示"),QString("请选中一个节点！"),QMessageBox::Yes);
    }

}


void MainWindow::on_pushButton_2_clicked()
{
    if(ui->lineEdit->text().length() == 0)
    {
        QMessageBox::information(this,QString("提示"),QString("必须输入内容"),QMessageBox::Yes);
        return;
    }
    QString itemtext = ui->lineEdit->text();
    ui->lineEdit->clear();
    // 如果列表元素为空则直接添加
    if(model->rowCount()==0){
        QStandardItem *item = new QStandardItem(itemtext);
        model->setItem(0,0,item);
    }
    // 列表不为空了添加
    else if(ui->treeView->currentIndex().isValid())
    {
        ui->treeView->currentIndex();
        QStandardItem *upper = model->itemFromIndex(ui->treeView->currentIndex())->parent();
        if(upper==NULL)
            model->appendRow(new QStandardItem(itemtext));
        else
            upper->appendRow(new QStandardItem(itemtext) );
    }
    else
    {
        QMessageBox::information(this,QString("提示"),QString("请选中一个节点！"),QMessageBox::Yes);
    }
}
